<?php

namespace App\Service\jump;
use App\Model\Applet;
use App\Model\DataSpread;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use GuzzleHttp\Client;
class JumpService extends CommicService
{
    //获取tokenurl
    public static $getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    public static $getSchemeUrl = "https://api.weixin.qq.com/wxa/generatescheme";

    //上传媒资视频接口-拉取上传

    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\RedisFactory::class)->get('wx');
    }
    /**
     * 获取token
     */
    public function getWxAccessToken($applet_id){
        $key = 'wx_access_token';
        $key .= $applet_id;
        $accessToken = $this->redisService->get($key);
        if(empty($accessToken)){
            $wxAppid = '';
            $wxSecret = '';
            # 获取小程序基本信息
            $appletInfo = Applet::query()->where(["id"=>$applet_id])->first()->toArray();
            if(!empty($appletInfo)){
                $wxAppid = $appletInfo['app_id'];
                $wxSecret = $appletInfo['app_secret'];
            }

            $params         = [
                'grant_type' => 'client_credential',
                'appid'    => $wxAppid,
                'secret'   => $wxSecret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'GET');

            if (!empty($accessTokenInfo['access_token'])){
                $accessToken = $accessTokenInfo['access_token'];
                $this->redisService->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        return $accessToken;
    }
    /**
     * 获取短剧的信息
     */
    public function getUrl(int $applet_id,$spreadInfo){
        $accessToken = $this->getWxAccessToken($applet_id);
        if(!empty($accessToken)){
           $url =  $this->getSchemeUrl($accessToken,$spreadInfo);
           return $url;
        }else{
            return false;
        }
    }
    public function getSchemeUrl($accessToken,$spreadInfo){
        $query = "spread_id=".$spreadInfo->id.'&pid='.$spreadInfo->playlet_id.'&peid='.$spreadInfo->playlet_number.'&aid='.$spreadInfo->user_id.'&ut='.$spreadInfo->user_type;
        $params = [
                "jump_wxa" =>[
                    "path"=> "/pages/videopage/videopage",
                    "query"=> $query,
                    "env_version"=> "release"
                ],
                "is_expire" => true,
                "expire_type" => 1,
                "expire_interval" => 1
        ];
        $schemeUrl = self::$getSchemeUrl.'?access_token='.$accessToken;
        $postResult  = $this->request($params, $schemeUrl,'POST');
        if($postResult['errcode'] == 0){
            return $postResult['openlink'];
        }else{
            return false;
        }
    }


    function request(array $params, string $url,string $method,$is_multipart = false)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        if ($is_multipart) {
            $headers       =['Content-Type' => 'multipart/form-data'];
        }else{
            $headers       =['Content-Type' => 'application/json;charset=utf-8', 'Accept' => 'application/json','Accept-Charset' => 'utf-8'];
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            if ($is_multipart) {
                $requestParams['multipart'] = $params;
            } else  {
                $requestParams['body'] = json_encode($params,JSON_UNESCAPED_UNICODE);
            }
        }

        $response = $client->request($method,$url, $requestParams);

        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }

}